package com.common.file;


import org.apache.commons.io.IOUtils;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.WritableResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Created by lzb on 2018/1/17.
 * 服务间文件上传的透传
 */
public class ByteUploadResource extends AbstractResource implements WritableResource  {

    private ByteArrayInputStream is;
    private ByteArrayOutputStream os;

    @Override
    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    private String filename;

    public ByteUploadResource(MultipartFile file) throws IOException {
        filename=file.getOriginalFilename();
        this.os=new ByteArrayOutputStream();
        IOUtils.copy(file.getInputStream(),this.os);
        this.os.flush();
        this.is=new ByteArrayInputStream(os.toByteArray());
    }

    public ByteUploadResource(File file) throws IOException {
        this.filename=file.getName();
        this.os=new ByteArrayOutputStream();
        IOUtils.copy(new FileInputStream(file),this.os);
        this.os.flush();
        this.is=new ByteArrayInputStream(os.toByteArray());
    }

    public ByteUploadResource(InputStream inputStream,String filename) throws IOException {
        this.filename=filename;
        this.os=new ByteArrayOutputStream();
        IOUtils.copy(inputStream,this.os);
        this.os.flush();
        this.is=new ByteArrayInputStream(os.toByteArray());
    }

    public ByteUploadResource(InputStream is) throws IOException {
        this.os=new ByteArrayOutputStream();
        IOUtils.copy(is,this.os);
        this.os.flush();
        this.is=new ByteArrayInputStream(os.toByteArray());
    }

    public ByteUploadResource(byte[] data) throws IOException {
        this.is=new ByteArrayInputStream(data);
        this.os=new ByteArrayOutputStream();
        IOUtils.copy(is,this.os);
        this.os.flush();
    }

    @Override
    public boolean isWritable() {
        return true;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return this.os;
    }

    @Override
    public String getDescription() {
        return "upload";
    }

    @Override
    public InputStream getInputStream() throws IOException {
        this.is=new ByteArrayInputStream(this.os.toByteArray());
        return this.is;
    }

    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public long contentLength() throws IOException {
        return os.size();
    }

    @Override
    public boolean exists() {
        return true;
    }

    @Override
    public boolean isReadable() {
        return true;
    }
}
